package service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import dao.OrdersDao;
import model.OrderItem;
import model.Orders;
import model.Page;
import utils.DataSourceUtils;

public class OrdersService {
	
	private  OrdersDao oDao = new OrdersDao();
	
	public void addOrders(Orders orders) {
		
		Connection con = null;
		try {
			con	= DataSourceUtils.getConnection();
			con.setAutoCommit(false); // 开启事务，不自动提交
			
			oDao.insertOrders(con, orders);
			int id = oDao.getLastInsertId(con);
			orders.setId(id);
			for(OrderItem item  : orders.getItemMap().values()) {
				
				oDao.insertOrderItem(con, item); // 进行遍历，获取里面所有的值
				
			}
			
			
			con.commit(); // 设置自动提交
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			if(con!=null)
				try {
					con.rollback();	// 进行事务回滚
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} 
		}
		
		
	}
	
	public List<Orders> selectAll(int userid) {
		
		List<Orders> list=null;
		
		try {
			list = oDao.selectAll(userid);
			for(Orders o : list) {
				
			List<OrderItem> l = oDao.selectAllItem(o.getId());
			o.setItemList(l);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	public Page getOrdersPage(int status,int pageNo) {
		
		Page	p  = new	Page();
		p.setPageNo(pageNo);
		int  pageSize  = 6;
		int		totalCount	= 0;
		try {
			totalCount = oDao.getOrdersCount(status);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		p.setPageSizeAndTotalCount(pageSize, totalCount);
		List list = null;
		
		try {
		list = oDao.selectOrdersList(status, pageNo, pageSize);
		for(Orders o : (List<Orders>)list) {
			
			List<OrderItem> l = oDao.selectAllItem(o.getId());
			o.setItemList(l);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		p.setList(list);
		return  p;
	}

	public void  updateStatus(int id,int status) {
		
		try {
			oDao.updateStatus(id, status);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public  void  delete(int id) {
		
	Connection  con  = null;
	try {
		 con = DataSourceUtils.getDataSource().getConnection(); // 进行事务
		con.setAutoCommit(false);  // 开启事务
		
		oDao.deleteOrdersItem(con, id); // 先删除订单项
		oDao.deleteOrders(con, id); // 再删除订单
		
		con.commit();  // 两个同时成功，则提交事务
		
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		if(con!=null)
			try {
				con.rollback();	// 否则就进行事务的回滚	
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
	}
	
		
	}
	
}
